<!-- 公司部门组件 -->
<template>
  <div class="fks-org-selector-page" :style="{ width }">
    <!-- label-in-value -->
    <a-tree-select
      v-bind="$attrs"
      v-model="selected"
      :allow-search="true"
      :allow-clear="true"
      :data="treeData"
      :filter-tree-node="filterTreeNode"
      :fallback-option="fallback"
      placeholder="请选择部门"
      :style="{ width }"
      @change="change"
    ></a-tree-select>
  </div>
</template>

<script lang="ts" setup>
  // TODO: 不支持多选，未加入deptName
  import { TreeNodeData } from '@arco-design/web-vue/es/tree/interface';
  import { ref, watch } from 'vue';
  import {
    getOrgs,
    OrgServiceRecord,
  } from '@/views/organization/department/api';
  import { LabelValue } from '@arco-design/web-vue/es/tree-select/interface';

  const props = defineProps({
    width: {
      type: String,
      default: '100%',
    },
    urlPath: {
      type: String,
      default: '/sys-user/orgs/tree',
    },
    deptId: {
      type: String,
      default: '0',
    },
    deptName: {
      type: String,
      default: '',
    },
  });

  const emit = defineEmits(['update:deptId', 'change']);
  const selected = ref(props.deptId);
  watch(
    () => props.deptId,
    (n) => {
      selected.value = n;
    }
  );
  const fallback = (key: string | number): TreeNodeData | boolean => {
    return { key, title: '根节点' };
  };

  let originData: OrgServiceRecord[] = [];
  const treeData = ref<TreeNodeData[]>([]);
  // fetch org data
  const fetchData = async () => {
    try {
      const { data }: { data: OrgServiceRecord[] } = await getOrgs();
      // 保存原始数据
      originData = data;
      treeData.value = tranferTreeData(data);
    } catch (err) {
      // eslint-disable-next-line no-console
      console.log(err);
    }
  };

  // 将接口树数据转换为组件树数据
  const tranferTreeData = (data: OrgServiceRecord[]) => {
    const result: TreeNodeData[] = [];
    data.forEach((item) => {
      const { children, content, id } = item;
      const obj: TreeNodeData = {
        key: id,
        title: content.name,
      };
      if (children && children.length) {
        const childrenRes = tranferTreeData(children);
        obj.children = childrenRes;
      }
      result.push(obj);
    });
    return result;
  };

  // 根据name过滤数据
  const filterTreeNode = (searchValue: string, nodeData: TreeNodeData) => {
    const title = nodeData.title || '';
    return title.toLowerCase().indexOf(searchValue.toLowerCase()) > -1;
  };

  const change = (
    val:
      | string
      | number
      | (string | number)[]
      | LabelValue
      | LabelValue[]
      | undefined
  ) => {
    // selected.value = val;
    emit('update:deptId', val);
    const otherVal = getOtherValue(val as string);
    emit('change', otherVal);
    // if (val.length == 0) {
    //   this.$emit('update:deptId', '')
    //   this.$emit('update:deptName', '')
    // } else {
    //   val.forEach(item => {
    //     dptNameStr += item.content.name + ','
    //     dptIdStr += item.id + ','
    //   })
    //   this.$emit('update:deptId', dptIdStr.substring(0, dptIdStr.length - 1))
    //   this.$emit(
    //     'update:deptName',
    //     dptNameStr.substring(0, dptNameStr.length - 1)
    //   )
    //   this.$emit('change', val)
    // }
  };

  // 根据id循环原始数据，获取其他值
  const getOtherValue = (id: string) => {
    let result: OrgServiceRecord | undefined;
    const loop = (data: OrgServiceRecord[]) => {
      data.forEach((item) => {
        const { children, id: itemId } = item;
        if (itemId === id) {
          result = item;
          return;
        }
        if (children && children.length) {
          loop(children);
        }
      });
    };
    loop(originData);
    return result;
  };

  fetchData();
</script>

<script lang="ts">
  // <span>Fallthrough attribute: {{ $attrs }}</span>
  // 使用普通的 <script> 来声明选项
  export default {
    name: 'OrgSelector',
    inheritAttrs: false,
  };
</script>
